﻿using AI.Graph;
using UnityEngine;

[CreateNodeMenu ("States/Follow")]
public class FollowState : State {

    [ParameterType (typeof (NavMeshMovement), "Nav Mesh Movement")]
    public ExposedParameter navMeshMovementParameter;

    [ParameterType (typeof (GameObject), "Follow Object")]
    public NodeParameter followObjectParameter;

    public float speed = 1;
    public float stoppingDistance = 0;

    private NavMeshMovement navMeshMovement;
    private GameObject followObject;
    private float lastSpeed;


    protected override void OnStateEnter (AIBehaviour aiBehaviour) {
        if (aiBehaviour.TryGetExposedObject (navMeshMovementParameter, out navMeshMovement)) {
            lastSpeed = navMeshMovement.speed;
        }
        else {
            Debug.Log ("No NavMeshMovement found on Follow State");
        }

        if (!aiBehaviour.TryGetValue (followObjectParameter, out followObject)) {
            Debug.Log ("No followed target.");
        }
    }


    protected override void OnStateUpdate (AIBehaviour aiBehaviour) {
        if (navMeshMovement != null && followObject != null) {
            navMeshMovement.speed = speed;
            navMeshMovement.MoveToDestination (followObject.transform.position, stoppingDistance);
        }
    }


    protected override void OnStateExit (AIBehaviour aiBehaviour) {
        if (navMeshMovement != null) {
            navMeshMovement.speed = lastSpeed;
        }
    }

}